from strategy.StrategyTemplate import StrategyTemplate
from utils.jsl_data_map import default_columns
# from database.lhjy import engine
from strategy import strategy_filter
from utils.simple_utls import code_fix
import pandas as pd


class Dao2(StrategyTemplate):
    """
    道哥转债池2:
        活跃债
        100元-130元之间，3天之内的平均换手
    """

    def __init__(self):
        super(Dao2, self).__init__()
        self.strategy_name = "活跃债策略"
        self.strategy_descrption = "130元以下转债按照活跃度由高到低排名"

    def run(self):
        self.data = strategy_filter.filter_base(self.data)
        self.data = self.data.loc[(self.data['现价'] > 100) & (self.data['现价'] < 130)]

        filter_list = []
        for code in self.data['转债代码']:
            code_with_pre = code_fix(code)
            try:
                if code_with_pre is not None:
                    temp = pd.read_sql_table(code_with_pre, con=engine)
                    temp = temp[['turnover_rt']]
                    temp = temp.tail(3)
                    avg_trunover_rt = (temp['turnover_rt'].astype('float').mean())
                    self.data.loc[self.data["转债代码"] == code, '平均换手'] = round(avg_trunover_rt, 2)
            except ValueError as e:
                pass
        self.data = self.data.sort_values(by='平均换手', ascending=False)
        # 获得默认列
        default_columns_extend = default_columns.copy()
        default_columns_extend.extend(['平均换手'])
        self.data = self.data[default_columns_extend]
        # 清掉原来的索引
        self.data.reset_index(inplace=True, drop=True)


if __name__ == '__main__':
    ins = Dao2()
    # ins.topN = 20
    ins.test()